package com.chezhujie.www.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chezhujie.www.core.StaticMap;
import com.chezhujie.www.core.weixin.HongBaoUtil;
import com.chezhujie.www.domain.*;
import com.chezhujie.www.domain.vo.AccessOpenId;
import com.chezhujie.www.domain.vo.WeixinInfo;
import com.chezhujie.www.enums.OrderStatus;
import com.chezhujie.www.enums.RunningStatus;
import com.chezhujie.www.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import weixin.popular.api.PayMchAPI;
import weixin.popular.bean.paymch.MchPayNotify;
import weixin.popular.bean.paymch.SecapiPayRefund;
import weixin.popular.bean.paymch.SecapiPayRefundResult;
import weixin.popular.client.LocalHttpClient;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;

/**
 * Created by 汤伟杰 on 2017/5/11.
 */
@Service
public class WeixininfoService {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private CzjweixinvoucherService czjweixinvoucherService;
    @Autowired
    private CzjorderService czjorderService;
    @Autowired
    private CzjactivityService czjactivityService;
    @Autowired
    private CzjtordermemberService czjtordermemberService;
    @Autowired
    private CzjmemberService czjmemberService;
    @Autowired
    private CzjorderdetailService czjorderdetailService;

    @Autowired
    private CzjcommodityService czjcommodityService;
    @Autowired
    private CzjorderdistributionService czjorderdistributionService;
    @Autowired
    private CzjawarduseService czjawarduseService;
    @Autowired
    private  CzjweixininfoService czjweixininfoService;
    @Autowired
    private  CzjusecouponService czjusecouponService;


    /**
     * 删除微信信息token缓存
     */
    public void checkCodeEndtime() {
       /* Map<String, String> map = StaticMap.getAccessOpenIdMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if(entry.getValue()==null){
                map.remove(entry.getKey());
            }else{
                AccessOpenId vo = JSONObject.parseObject(entry.getValue(),AccessOpenId.class);
                if(vo.getEndtime()-System.currentTimeMillis()>=0){
                    map.remove(entry.getKey());
                }
            }

        }*/
    }

    /**
     * 刷新code值
     * @param code
     * @return
     */
    public void getRefreshAccessToken(String code,String appid) throws Exception {
        AccessOpenId openIdEntity = StaticMap.getAccessOpenIdMap(code);
        String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+appid+"&grant_type=refresh_token&refresh_token="+openIdEntity.getRefresh_token();
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"请求刷新token:"+url);
        Map<String, Object> refresh_token = CommonHttp.send(url, "get", null);
        if(refresh_token.get("errcode")!=null){
            throw new Exception("请求刷新token失败！返回值："+JSONObject.toJSONString(refresh_token));
        }
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"返回值:"+JSONObject.toJSONString(refresh_token));
        setOpenIdEntity(refresh_token,code);

    }

    /**
     *
     * @param code
     * @return
     * {
    "access_token":"ACCESS_TOKEN",
    "expires_in":7200,
    "refresh_token":"REFRESH_TOKEN",
    "openid":"OPENID",
    "scope":"SCOPE",
    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
    }
     */
    public void getAccessToken(String code,String appid,String secret) throws Exception {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"请求token:"+url);
        Map<String, Object> access_token_map = CommonHttp.send(url, "get", null);
        if(access_token_map.get("errcode")!=null){
            throw new Exception("请求token失败！返回值："+JSONObject.toJSONString(access_token_map));
        }
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"返回值:"+JSONObject.toJSONString(access_token_map));
        setOpenIdEntity(access_token_map,code);

    }
    public void getWeixinInfoByToken(String code) throws Exception {
        AccessOpenId openIdEntity = StaticMap.getAccessOpenIdMap(code);
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+openIdEntity.getAccess_token()+"&openid="+openIdEntity.getOpenid()+"&lang=zh_CN";
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"请求微信信息:"+url);
        Map<String, Object> weixinInfo = CommonHttp.send(url, "get", null);
        if(weixinInfo.get("errcode")!=null){
            throw new Exception("请求token获取微信用户信息失败！返回值："+JSONObject.toJSONString(weixinInfo));
        }
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"返回值:"+JSONObject.toJSONString(weixinInfo));
        setWeixinInfo(weixinInfo,openIdEntity.getOpenid());


    }
    private void setOpenIdEntity(Map<String,Object> data,String code){
        AccessOpenId openIdEntity = StaticMap.getAccessOpenIdMap(code);
        if(openIdEntity==null){
            openIdEntity = new AccessOpenId();
        }
        openIdEntity.setAccess_token(String.valueOf(data.get("access_token")));
        openIdEntity.setCode(code);
        openIdEntity.setCreatetime(new Date());
        openIdEntity.setExpires_in(Long.valueOf(String.valueOf(data.get("expires_in"))));
        openIdEntity.setScope(String.valueOf(data.get("scope")));
        openIdEntity.setUnionid(String.valueOf(data.get("unionid")));
        openIdEntity.setOpenid(String.valueOf(data.get("openid")));
        openIdEntity.setRefresh_token(String.valueOf(data.get("refresh_token")));
        openIdEntity.setEndtime(System.currentTimeMillis()+openIdEntity.getExpires_in()*1000);
        StaticMap.getAccessOpenIdMap().put(code, JSONObject.toJSONString(openIdEntity));
    }

    public void setWeixinInfo(Map<String,Object> weixinInfoMap,String openid) {
        String json = StaticMap.getWeixinInfoJson(openid);

        if(json==null){
            //保存到缓存里
            weixinInfoMap.put("update", 1);
            StaticMap.getWeixinInfoJson().put(openid, JSONObject.toJSONString(weixinInfoMap));
        }else {
            Map<String,Object> mapType = JSON.parseObject(json,Map.class);
            if(String.valueOf(mapType.get("nickname")).equals(String.valueOf(weixinInfoMap.get("nickname")))
                    ||String.valueOf(mapType.get("headimgurl")).equals(String.valueOf(weixinInfoMap.get("headimgurl")))
                    ||String.valueOf(mapType.get("province")).equals(String.valueOf(weixinInfoMap.get("province")))
                    ||String.valueOf(mapType.get("city")).equals(String.valueOf(weixinInfoMap.get("city")))
                    ||String.valueOf(mapType.get("country")).equals(String.valueOf(weixinInfoMap.get("country")))
                    ){
                weixinInfoMap.put("update","1");//告诉他要更新数据库中的数据
            }
            //保存到缓存里
            StaticMap.getWeixinInfoJson().put(openid, JSONObject.toJSONString(weixinInfoMap));

        }
    }

    /**
     * URL 转码
     *
     * @return String
     * @author lifq
     * @date 2015-3-17 下午04:10:28
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String getAccessToken() throws Exception {

        String uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+StaticMap.appid+"&secret="+StaticMap.secret;
        Map<String,Object> map = null;
        try {
            map = CommonHttp.send(uri, "get", null);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取 access_token 失败!");
        }
//        System.out.println(JSONObject.toJSONString(map));
        StaticMap.getAccessToken().setCreatetime(new Date());
        StaticMap.getAccessToken().setExpires_in(Integer.parseInt(String.valueOf(map.get("expires_in"))));
        StaticMap.getAccessToken().setEndtime(new Date().getTime()+(StaticMap.getAccessToken().getExpires_in()*1000));
        return  String.valueOf(map.get("access_token"));
//        map.get("expires_in");
    }
    public static String getTicket(String access_token) throws Exception {

        String uri = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
        Map<String,Object> map = null;
        try {
            map = CommonHttp.send(uri, "get", null);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取 ticket 失败!");
        }
        if((Integer)map.get("errcode")==1){
            throw new Exception("获取 ticket 失效!");
        }
        return  String.valueOf(map.get("ticket"));

    }


    public static Map<String, Object> sign(String jsapi_ticket, String url,String appid) throws DigestException {
        Map<String, Object> ret = new HashMap<String, Object>();
        String nonce_str = create_nonce_str();
        Long timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+string1);

        signature=SHA1(string1);


        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appid", appid);

        return ret;
    }


    /**
     * SHA1 安全加密算法
     *
     * @return
     * @throws DigestException
     */
    public static String SHA1(String decrypt) throws DigestException {
        //获取信息摘要 - 参数字典排序后字符串
//        String decrypt = getOrderByLexicographic(maps);
        try {
            //指定sha1算法
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(decrypt.getBytes());
            //获取字节数组
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString().toLowerCase();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new DigestException("签名错误！");
        }
    }

    private static String create_nonce_str() {
//        return UUID.randomUUID().toString();
        return UUIDUtils.getUUID();
    }


    private static Long create_timestamp() {
        return System.currentTimeMillis() / 1000;
    }
    public WeixinInfo getWeixinInfo(String code, String appid, String secret) throws Exception {
        AccessOpenId openIdEntity = StaticMap.getAccessOpenIdMap(code);
        //设置token

        checkCodeEndtime();
        if(openIdEntity==null){
            getAccessToken(code,appid,secret);//得到token
            getWeixinInfoByToken(code);//得到微信信息
        }else if(openIdEntity.getEndtime()<=System.currentTimeMillis()){
            getRefreshAccessToken(code,appid);//刷新token
            getWeixinInfoByToken(code);//得到微信信息
        }
        //从缓存获取微信信息
        StaticMap.getAccessOpenIdMap();
        StaticMap.getWeixinInfoJson();
        openIdEntity = StaticMap.getAccessOpenIdMap(code);

        WeixinInfo weixinInfo = StaticMap.weixinInfoJsonTo(openIdEntity.getOpenid());
        
       saveWeixin(weixinInfo);
        return weixinInfo;
    }

    public void saveWeixin(WeixinInfo weixinInfo) throws UnsupportedEncodingException {
        Czjweixininfo czjweixininfo = new Czjweixininfo();
        czjweixininfo.setCity(weixinInfo.getCity());
        czjweixininfo.setOpenid(weixinInfo.getOpenid());
        czjweixininfo.setCountry(weixinInfo.getCountry());
        czjweixininfo.setCreatetime(new Date());
        czjweixininfo.setHeadimgurl(weixinInfo.getHeadimgurl());

        czjweixininfo.setSex(weixinInfo.getSex());
        czjweixininfo.setPrivilege(null);
        czjweixininfo.setProvince(weixinInfo.getProvince());
        czjweixininfo.setUnionid(weixinInfo.getUnionid());
        czjweixininfo.setNickname("");
        czjweixininfoService.save(czjweixininfo);
        String nickname = weixinInfo.getNickname();
        czjweixininfo.setNickname(nickname);

        try {
            czjweixininfoService.update(czjweixininfo);
        } catch (Exception e) {
            System.out.println(LocalDateTime.now()+"    "+e);
//            e.printStackTrace();
        }
    }

    public WeixinInfo getWeixinUserInfoByOpenid(String openid) throws Exception {

        Czjweixininfo czjweixininfo = (Czjweixininfo)jdbcTemplate.queryForObject("select * from czj_weixininfo where openid='" + openid + "'", new BeanPropertyRowMapper(Czjweixininfo.class));
        WeixinInfo weixinInfo = new WeixinInfo();
        weixinInfo.setOpenid(czjweixininfo.getOpenid());
        weixinInfo.setNickname(czjweixininfo.getNickname());
        weixinInfo.setSex(czjweixininfo.getSex());
        weixinInfo.setProvince(czjweixininfo.getProvince());
        weixinInfo.setCity(czjweixininfo.getCity());
        weixinInfo.setCountry(czjweixininfo.getCountry());
        weixinInfo.setHeadimgurl(czjweixininfo.getHeadimgurl());
        weixinInfo.setUnionid(czjweixininfo.getUnionid());
        return weixinInfo;
    }

    public Map<String,Object> getWeixinGongzhonghao(String code,String appid,String secret) throws Exception {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("subscribe", 0);
        Map<String, Object> tokenmap = getAccessTokenGzh();
        getWeixinInfo(code, appid, secret);
        AccessOpenId access = StaticMap.getAccessOpenIdMap(code);
        String openid=access.getOpenid();
        String token = String.valueOf(tokenmap.get("access_token"));

        Map<String, Object> weixininfoMap = getFocusWeixinGzh(token, openid);
        if(Integer.valueOf(String.valueOf(weixininfoMap.get("subscribe")))==1){
            map.put("subscribe", 1);
        }
        return map;
    }

    /**
     * 获取token（和是否关注微信公众号关联）
     * @return
     * @throws Exception
     */
    public Map<String, Object> getAccessTokenGzh() throws Exception {
        System.out.println(LocalDateTime.getDateStr(new Date())+"    请求token！"+"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+StaticMap.appid+"&secret="+StaticMap.secret);
        Map<String,Object> tokenmap = CommonHttp.send("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+StaticMap.appid+"&secret="+StaticMap.secret, "get", null);
        if(tokenmap.get("errcode")!=null){
            throw new Exception("请求token失败！返回值："+JSONObject.toJSONString(tokenmap));
        }
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+JSONObject.toJSONString(tokenmap));
        return tokenmap;
    }
    /**
     * 获取是否关注微信公众号
     * @param token
     * @param openid
     * @return
     * @throws Exception
     */
    public Map<String,Object> getFocusWeixinGzh(String token,String openid) throws Exception {
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"获取是否关注微信公众号：https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openid + "&lang=zh_CN");
        Map<String, Object> map = CommonHttp.send("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openid + "&lang=zh_CN", "get", null);
        if(map.get("errcode")!=null){
            throw new Exception("获取公众号个人信息失败！返回值："+JSONObject.toJSONString(map));
        }
        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+"返回："+JSONObject.toJSONString(map));
        return map;
    }




    public void insertWeixinVoucher(MchPayNotify payNotify) throws Exception {
        Czjweixinvoucher entity = new Czjweixinvoucher();
        entity.setAppid(payNotify.getAppid());
        entity.setAttach(payNotify.getAttach());
        entity.setBank_type(payNotify.getBank_type());
        entity.setCash_fee(payNotify.getCash_fee());
        entity.setCash_fee_type(payNotify.getCash_fee_type());
        entity.setCoupon_count(payNotify.getCoupon_count());
        entity.setCoupon_fee(payNotify.getCoupon_fee());
        entity.setCoupon_fee_n(null);//代金券
        entity.setCoupon_id_n(null);//代金券
        entity.setCoupon_type_n(null);//代金券
        entity.setErr_code(payNotify.getErr_code());
        entity.setErr_code_des(payNotify.getErr_code_des());
        entity.setFee_type(payNotify.getFee_type());
        entity.setIs_subscribe(payNotify.getIs_subscribe());
        entity.setMch_id(payNotify.getMch_id());
        entity.setNonce_str(payNotify.getNonce_str());
        entity.setOpenid(payNotify.getOpenid());
        entity.setOut_trade_no(payNotify.getOut_trade_no());
        entity.setResult_code(payNotify.getResult_code());
        entity.setSettlement_total_fee(payNotify.getSettlement_total_fee());
        entity.setSign(payNotify.getSign());
        entity.setTime_end(payNotify.getTime_end());
        //微信传过来是没有小数的，都是整数，所以要除以100并保存2位小数
        entity.setTotal_fee(new BigDecimal(payNotify.getTotal_fee()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));//支付金额
        entity.setTrade_type(payNotify.getTrade_type());
        entity.setTransaction_id(payNotify.getTransaction_id());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        entity.setPaytime(sdf.parse(entity.getTime_end()));
        entity.setRunningStatus(RunningStatus.RUNNING.getIndex());
        czjweixinvoucherService.insert(entity);
        insertOrder(payNotify, entity);

    }

    private  void insertOrder(MchPayNotify payNotify, Czjweixinvoucher entity) throws Exception{
        String couponsId = null;
        Integer userinfoId = null;
        try {

            String orderno = payNotify.getOut_trade_no();
            //修改订单状态为已支付
            String type = orderno.substring(8, 9);
            if("1".equals(type)){
                Map<String,Object> resultMap = czjactivityService.getOrderedByNo(orderno);
                if(resultMap.get("couponsId")==null){
                    couponsId = null;
                }else{
                    couponsId = String.valueOf(resultMap.get("couponsId"));
                }
                userinfoId = Integer.parseInt(String.valueOf(resultMap.get("userinfoId")));
                czjactivityService.updateOrderStatus(orderno, OrderStatus.UNUSE.getIndex());
            }else if("2".equals(type)){
                Map<String,Object> resultMap = czjorderService.getOrderedByNo(orderno);
                if(resultMap.get("couponsId")==null){
                    couponsId = null;
                }else{
                    couponsId = String.valueOf(resultMap.get("couponsId"));
                }
                Czjorderdetail czjorderdetail = czjorderdetailService.queryByCode(orderno);
                if(czjorderdetail==null||czjorderdetail.getCommodityId()==null){
                    throw new Exception("商品订单详情不存在！或者商品订单详情中的商品不存在！！！");
                }

                //增加已售量
                Czjcommodity comodity = czjcommodityService.queryById(czjorderdetail.getCommodityId());
                if(comodity.getSoldCount()==null){
                    comodity.setSoldCount(0);
                }
                if(czjorderdetail.getAmount()==null){
                    throw new Exception("商品订单购买数量不能为空，异常订单！！！");
                }
               /* comodity.setInventory(comodity.getInventory()-czjorderdetail.getAmount());
                if(comodity.getInventory()<0){
                    throw new Exception("该商品已售完");
                }*/
                comodity.setSoldCount(comodity.getSoldCount()+czjorderdetail.getAmount());
                userinfoId = Integer.parseInt(String.valueOf(resultMap.get("userinfoId")));
                czjcommodityService.update(comodity);
                Czjorderdistribution orderdistribution = czjorderdistributionService.getByOrderno(orderno);
                if(orderdistribution==null){
                    czjorderService.updateOrderStatus(orderno,OrderStatus.FIN.getIndex());
                }else{
                    czjorderService.updateOrderStatus(orderno,OrderStatus.TOSENDGOODS.getIndex());
                }




            }else{
                throw new Exception("该订单号不是活动订单或者商品订单！");
            }

            if(StringUtils.isNotBlank(couponsId)){
                //使用后更改优惠券状态为已使用
                Czjawarduse czjawarduse32 = new Czjawarduse();
                czjawarduse32.setAwarduseId(couponsId);
                Czjawarduse czjawarduse = czjawarduseService.getCzjawarduse(ConvertObj.toMap(czjawarduse32));
                czjawarduse.setStatus(OrderStatus.USE.getIndex());
                czjawarduseService.updateCzjawarduse(czjawarduse);
                czjusecouponService.businessSave(couponsId, orderno);
            }
            entity.setRunningStatus(RunningStatus.SUCCESS.getIndex());
            entity.setUserinfoId(userinfoId);
            czjweixinvoucherService.update(entity);

        } catch (Exception e) {
            e.printStackTrace();
            entity.setRunningStatus(RunningStatus.FAILED.getIndex());
            entity.setUserinfoId(userinfoId);
            czjweixinvoucherService.update(entity);
        }
    }

    /** 退款 */
    public SecapiPayRefundResult payRefund(String orderno) throws Exception{
        Czjweixinvoucher czjweixinvoucher = czjweixinvoucherService.queryByOrderno(orderno);
        SecapiPayRefund secapiPayRefund = new SecapiPayRefund();
        secapiPayRefund.setAppid(czjweixinvoucher.getAppid());
        secapiPayRefund.setMch_id(czjweixinvoucher.getMch_id());
        secapiPayRefund.setNonce_str(czjweixinvoucher.getNonce_str());
        secapiPayRefund.setSign_type("HMAC-SHA256");
        secapiPayRefund.setTransaction_id(czjweixinvoucher.getTransaction_id());
        secapiPayRefund.setOut_trade_no(czjweixinvoucher.getOut_trade_no());
        secapiPayRefund.setOut_refund_no(czjweixinvoucher.getTransaction_id());
        secapiPayRefund.setTotal_fee(czjweixinvoucher.getTotal_fee().multiply(new BigDecimal(100)).intValue());
        secapiPayRefund.setRefund_fee(0);
        secapiPayRefund.setRefund_fee(secapiPayRefund.getTotal_fee());

        secapiPayRefund.setRefund_fee_type("CNY");

        String filepath = this.getClass().getResource("/").getPath()+"/apiclient_cert.p12";
        LocalHttpClient.initMchKeyStore(czjweixinvoucher.getMch_id(),new FileInputStream(new File(filepath)));
        SecapiPayRefundResult secapiPayRefundResult = PayMchAPI.secapiPayRefund(secapiPayRefund, StaticMap.payKey);


        System.out.println(LocalDateTime.getDateStr(new Date())+"    "+ConvertObj.toMap(secapiPayRefundResult).toString());
        return secapiPayRefundResult;
    }



    public String sendredpack(String orderCode, String openId, String userinfoId, Integer amount, HttpServletRequest request) throws Exception {
        if(amount==null){
            amount=100;
        }
        SortedMap<String, String> sortedMap = HongBaoUtil.createMap(orderCode,openId, userinfoId, amount,request.getRemoteAddr());
        HongBaoUtil.sign(sortedMap);
        String postXML = HongBaoUtil.getRequestXml(sortedMap);
        System.out.println(postXML);
        String filepath = this.getClass().getResource("/").getPath()+"/apiclient_cert.p12";
        FileInputStream instream = new FileInputStream(new File(filepath));

        return HongBaoUtil.post(postXML, instream);
    }


}
